<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<div><el-button type="warning" class="item-gap" size="mini" :loading="exportLoading" @click="onReportBtn">导出</el-button></div>
				</div>
				<div class="flex-start-center">
					<jk-select v-model="searchParams.workshopId" disabled :clearable="false" placeholder="区域" :option-list="workshopList" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onWorkshopChange"></jk-select>
					<jk-select v-model="searchParams.processCode" disabled value-key-name="code" :clearable="false" :option-list="garbledProcess" placeholder="工序" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-date-picker v-model="searchParams.belongDate" :clearable="false" type="date" placeholder="日期" :picker-options="pickerOptions" class="search-bar-item-size2 margin-5-0 item-gap"></jk-date-picker>
					<jk-select v-model="searchParams.shiftId" :option-list="shiftList" placeholder="班次" size="small" class="search-bar-item-size1 margin-5-0 item-gap" clearable />
					<!--<jk-search-input v-model="searchParams.productNameOrCode" placeholder="品种编号或名称" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />-->
					<jk-search-input v-model="searchParams.machineNameOrCode" placeholder="机台编号或名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table ref="jkTable" border :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<time-list
							v-if="item.keyName === 'recordsList'"
							:data-list="scope.row.recordsList || []"
							@on-confirm="onConfirmBtn"
						></time-list>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<!--<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>-->
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { firstCharacterToLowerCase, pageConfig, formatDate, formatTime } from '/src/utils/jk/jk-tool';
    import handlerCache from '../../../mixins/handler-cache';
    import timeList from './components/time-list';
    import { productionMachineTonYarnEnergyDoffStatistics } from '../../../api/production/reports';
    import { workforceManagementShiftGetByTime, workforcemanagementShiftPage } from '../../../api/schedule/shift';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import { systemUserColumnConfigGet } from '../../../api/system/column-config';
    export default {
        name: 'ShiftProductEnergyConsumptionStatistics',
        components: {
            timeList
        },
        mixins: [calHeight, handlerCache, getMenuColumn],
        data() {
            return {
                apiItem: {
                    'page': productionMachineTonYarnEnergyDoffStatistics
                },
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                workshopList: [],
                tableLoading: true,
                shiftList: [],
                tableData: [],
                garbledProcess: [],
                processList: [],
                totalCount: 0,
                searchParams: {
                    // pageNo: pageConfig.pageNo,
                    // pageSize: pageConfig.pageSize,
                    workshopId: null,
                    machineNameOrCode: '',
                    processCode: '',
                    belongDate: ''
                },
                exportLoading: false
            };
        },
        methods: {
            onReportBtn() {
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                    const params = JSON.parse(JSON.stringify(this.searchParams));
                    delete params.pageNo;
                    delete params.pageSize;
                    return productionMachineTonYarnEnergyDoffStatistics(params).then(res => {
                        this.exportLoading = false;
                        if (res.data.status === 200) {
                            const resData = res.data.res || [];
                            const list = [];
                            resData.forEach(machineItem => {
                                if (machineItem.recordsList) {
                                    machineItem.recordsList.forEach(recordItem => {
                                        list.push({
                                            machineName: machineItem.machineName,
                                            doffCount: machineItem.doffCount,
                                            doffMinute: machineItem.doffMinute,
                                            startDateTime: recordItem.startDateTime,
                                            endDateTime: recordItem.endDateTime,
                                            timeMinute: recordItem.timeMinute
                                        });
                                    });
                                }
                            });
                            import('@/vendor/Export2Excel').then(excel => {
                                const tHeader = [
                                    '机台', '总落纱次数', '总落纱时长', '生产开始时间', '生产结束时间',
                                    '停机时长(分钟)', '停机原因'
                                ];
                                const filterVal = [
                                    'machineName', 'doffCount', 'doffMinute', 'startDateTime', 'endDateTime',
                                    'timeMinute'
                                ];
                                const data = list.map(v => filterVal.map(j => {
                                    return v[j];
                                }));
                                const processItem = this.processList.find(x => x.code === this.searchParams.processCode) || {};
                                const shiftItem = this.shiftList.find(x => x.code === this.searchParams.shiftId) || {};
                                excel.export_json_to_excel({
                                    header: tHeader,
                                    data,
                                    filename: `${processItem.name}-落纱统计 ${this.searchParams.belongDate}${shiftItem.shiftName || ''}`,
                                    autoWidth: true,
                                    bookType: 'xlsx'
                                });
                            });
                        }
                    });
                }).catch(() => {});
            },
            onWorkshopChange(val) {
                this.$set(this.searchParams, 'processCode', '');
                this.getProcessData(val);

                this.$set(this.searchParams, 'shiftId', null);
                this.shiftList = [];
                this.getShiftListByWorkshopRequest();
            },
            getProcessData(val) {
                this.garbledProcess = [];
                this.processList.forEach(y => {
                    if (val === y.workshopId) {
                        this.garbledProcess.push(y);
                    }
                });
            },
            onConfirmBtn() {
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            // 获取区域的班次
            getShiftListByWorkshopRequest() {
                this.shiftList = [];
                if (!this.searchParams.workshopId) return;
                return workforcemanagementShiftPage({
                    workshopId: this.searchParams.workshopId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                    }
                });
            },
            getCurrentShiftInfoRequest() {
                if (!this.searchParams.workshopId) return;
                return workforceManagementShiftGetByTime({
                    workshopId: this.searchParams.workshopId,
                    belongTime: formatTime(Date.now())
                }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        this.$set(this.searchParams, 'shiftId', resData.currentShiftInfo ? resData.currentShiftInfo.id : null);
                    }
                });
            },
            async getDependentData() {
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.processList = this.$store.state.user.userProcess.processList;
                if (!this.searchParams.belongDate) this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                // if (!this.searchParams.belongDate) this.$set(this.searchParams, 'belongDate', '2024-05-28');
                if (!this.searchParams.processCode) this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode);
                if (!this.searchParams.workshopId) this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                this.getProcessData(this.searchParams.workshopId);
                this.tableLoading = true;
                await this.getShiftListByWorkshopRequest();
                await this.getCurrentShiftInfoRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            getMenuColumnListRequest() {
                return systemUserColumnConfigGet({ path: firstCharacterToLowerCase(this.$route.name), filterShow: true }).then(res => {
                    if (res.data.status === 200) {
                        const arr = [];
                        this.tableData.forEach(x => {
                            arr.push(x.recordsList ? x.recordsList.length : 0);
                        });
                        const maxVal = Math.max(...arr);
                        const columnConfigList = res.data.res.columnConfigList && res.data.res.columnConfigList.length ? res.data.res.columnConfigList[0].itemList : [];
                        columnConfigList.forEach(x => {
                            // 动态计算"停机明细"的宽度
                            if (x.keyName === 'recordsList') {
                                x.minWidth = maxVal * 186;
                                delete x.width;
                            }
                        });
                        this.tableColumnList = columnConfigList;
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                return this.apiItem['page'](params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res || [];
                        this.totalCount = res.data.count;
                        this.getMenuColumnListRequest();
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            }
        },
        mounted() {
            this.processList = this.$store.state.user.userProcess.processList;
            this.getDependentData();
        }
    };
</script>
